package tree;

public class VerifyPreorderSerializationOfABinaryTree331 {
    public boolean isValidSerialization(String preorder) {
        String[] chars = preorder.split(",");
        if (chars == null || chars.length < 1) {
            return true;
        }
        if ("#".equals(chars[0])) {
            if(chars.length==1){
                return true;
            }else {
                return false;
            }
        }
        int count = 2;
        for (int i = 1; i < chars.length; i++) {
            if ("#".equals(chars[i])) {
                count--;
                if (count < 0) {
                    return false;
                }
            } else {
                count--;
                if (count < 0) {
                    return false;
                } else {
                    count = count + 2;
                }
            }

        }
        return count == 0;
    }
}
